<?php
/**
 * Created by PhpStorm.
 * Author: kaodou
 * Date: 2017/10/17
 * Time: 15:07
 */
namespace App\Http\Admin\OrderType\Controllers;

use Framework\BaseClass\Http\Admin\Controller;
use App\Http\Admin\Website\Models\Menu;
use App\Http\Admin\OrderType\Models\OrderType;
use App\Eloquent\Ygt\Process;
use App\Eloquent\Ygt\ProcessOrdertype;
use App\Engine\Func;
use App\Eloquent\Ygt\Permission;
use App\Eloquent\Ygt\Privilege;
use App\Eloquent\Ygt\OrdertypeCategory;

class IndexController extends Controller
{

    public function getOrderTypeList()
    {
        $adminUser          = request()->user('admin')->toArray();
        $company_id         = $adminUser['company_id'];
        if (request()->isMethod('post')) {
            $title          = request('title','');
            $where = [];
            $orderTypeModel = new orderType();
//            $orderTypeResult = $orderTypeModel->getOrderTypeList();

            $pageSize       = request('pageSize', 30);
            $pageCurrent    = request('pageCurrent', 1);
            $offset         = ($pageCurrent - 1) * $pageSize;

            $fields = '*';

            $where = [];
            $where['company_id'] = $company_id;
            if($title)
            {
                $where['title'] = ['like','%'.$title.'%'];
            }
            $orderTypeResult = $orderTypeModel->getData($where, $fields, '', '');
//            $orderTypeResult = $orderTypeModel->getOrderTypeList();
            $orderTypeResult->transform(function ($item, $key) {
                $item->img_url = Func::getImgUrlById($item->img_id);
//                $item->created_time = $item->created_at->formatLocalized('%Y-%m-%d %H:%M:%S');
                return $item;
            });

            $count = $orderTypeModel->getCount($where);
            $result = collect(['totalRow'=>$count,'pageCurrent'=>$pageCurrent,'list'=>$orderTypeResult]);

            return $result->toJson();
        }

        $orderTypeCategoryModel = new OrdertypeCategory();
        $categoryList = $orderTypeCategoryModel->getData(['company_id'=>$company_id],'id,cat_name')->toArray();
        $categoryListJson = [];
        foreach ($categoryList as $v){
            $categoryListJson[$v['id']] = $v['cat_name'];
        }
        $categoryListJson = json_encode($categoryListJson);

        return $this->view('list',compact('categoryListJson'));
    }

    public function setOrderTypeProcess(){
        if (request()->isMethod('post')) {
            $orderTypeId = request('ordertype_id');
            $steps = request('step');
            $processIds = request('process_id');
            foreach ($processIds as $step_number=>$cprocess){
                foreach ($cprocess as $key => $val){
                    $cdata[] = [
                        'ordertype_id'=>$orderTypeId,
                        'process_id'=>$val,
                        'step_number'=>$step_number,
                    ];
                }

            }

            $delData = ['ordertype_id'=>$orderTypeId];

            $processOrdertypeModel = new ProcessOrdertype();

            //删除没有设置步骤的工序
            $processOrdertypeModel->del($delData);


            if($processOrdertypeModel->addProcessOrderType($cdata)){
                return $this->jsonReturn('ok');
            }

        }else{
            $orderTypeId = request('orderTypeId');
            $ProcessModel = new Process();
            $adminUser          = request()->user('admin')->toArray();
            $company_id         = $adminUser['company_id'];

            $processList = $ProcessModel->getData(['is_last'=>1,'company_id'=>$company_id]);

            return $this->view('set-process', compact('orderTypeId','processList'));
        }

    }
    public function setOrderTypeProcessStep(){
        if (request()->isMethod('post')) {
            $id = request('id');
            $nextStepIds = request('next_steps',[]);
            $nextSteps = implode(',',$nextStepIds);
            if(in_array($id,$nextStepIds)){
                return $this->ajaxFail('不能把当前步骤设置为下一步');
            }
            $processOrdertypeModel = new ProcessOrdertype();
            $updateData = ['next_step'=>$nextSteps];
            $where = ['id'=>$id];
            $result = $processOrdertypeModel->updateOneData($where, $updateData);
            if($result){
                return $this->ajaxSuccess();
            }else{
                return $this->ajaxFail();
            }
        }
        $orderTypeId = request('orderTypeId');
        $id = request('id');
        $processList = $this->getOrderTypeProcessList($orderTypeId);

        $processOrdertypeModel = new ProcessOrdertype();
        $where = ['id'=>$id];
        $info = $processOrdertypeModel->getOneData($where);

        $nextStepIds = explode(',',$info['next_step']);
        $processList->transform(function ($item, $key) use($nextStepIds) {
            $item->isCheck = in_array($item->id,$nextStepIds) ? 1 : 0;
            return $item;
        });

        return $this->view('set-process-step', compact('orderTypeId','processList','id'));

    }

    private function getOrderTypeProcessList($orderTypeId){
        $processOrdertypeModel = new ProcessOrdertype();
        $join = [
            ['table'=>'ygt_process','field_l'=>'ygt_process.id','field_c'=>'=','field_r'=>'ygt_process_ordertype.process_id'],
        ];
        $adminUser          = request()->user('admin')->toArray();
        $company_id         = $adminUser['company_id'];

        $list = $processOrdertypeModel->getData(['ordertype_id'=>$orderTypeId,'company_id'=>$company_id],'ygt_process_ordertype.*,ygt_process.title', '', '', ['ygt_process_ordertype.step_number','asc'], '', $join);
        return $list;
    }
    //获取工艺中，工序列表，异步
    public function getOrderTypeProcessListWhitNextStep(){
        $orderTypeId = request('orderTypeId');
        $list = $this->getOrderTypeProcessList($orderTypeId);

        $allActions = collect(Permission::getTypeActionList( 1 ));
        $list->transform(function ($item, $key) use ($list,$allActions) {
            $nestSteps = explode(',',$item->next_step);

            $filtered = $list->whereIn('id', $nestSteps);
            $filtered = $filtered->map(function ($item) {
                return collect($item->toArray())->only('step_number','title');
            });

            //动作
            $item->nextSteps = $filtered->values()->all();
            $actions = explode(',',$item->actions);
            $actionArr = $allActions->reject(function ($item, $key) use($actions) {
                return !in_array($item['id'],$actions);
            });

            $item->actionArr = $actionArr->values();
            $item->actionStrs = implode(',',$actionArr->pluck('title')->toArray());

            $adminUser          = request()->user('admin')->toArray();
            $company_id         = $adminUser['company_id'];

            //权限
            $privilege         = collect(Privilege::getList( ['company_id'=>$company_id], 'id,title' )->toArray());

            $jurisdictions = explode(',',$item->role_jurisdiction);
            $jurisdictionArr = $privilege->reject(function ($item, $key) use($jurisdictions) {
                return in_array($item['id'],$jurisdictions);
            })->pluck('title');
            $item->jurisdictionStrs = implode(',',$jurisdictionArr->toArray());

            return $item;
        });

//        dd($list->toArray());

        return $list;
    }



    public function deleteOrderTypeProcess(){
        $id = request('id');
        $processOrdertypeModel = new ProcessOrdertype();
        if($processOrdertypeModel->del(['id'=>$id])){
            return $this->ajaxSuccess('删除成功');
        }else{
            return $this->ajaxFail('删除失败！');
        }
    }

    public function addOrderTypeProcess(){
        if (request()->isMethod('post')) {

            $processArr = request('process');
            $orderTypeId = request('orderTypeId');

            $processOrdertypeModel = new ProcessOrdertype();
            if ($maxStep = $processOrdertypeModel->getOneData(['ordertype_id' => $orderTypeId], '', ['step_number', 'desc'])) {

                $maxStepNumber = $maxStep->step_number;
            } else {
                $maxStepNumber = 0;
            }

            foreach ($processArr as $v) {
                $maxStepNumber++;
                $createData[] = ['ordertype_id' => $orderTypeId, 'process_id' => $v, 'step_number' => $maxStepNumber];
            }
            $result = $processOrdertypeModel->insertData($createData);
            if ($result) {
                return $this->ajaxSuccess('添加成功');
            } else {
                return $this->ajaxFail('添加失败，请重试！');
            }
        } else {
            $orderTypeId = request('orderTypeId');
            $ProcessModel = new Process();
            $adminUser = request()->user('admin')->toArray();
            $companyId = $adminUser['company_id'];

            $processTypeList        = config('process.process_type_list');
            $where                  = ['is_last'=>1,'company_id'=>$companyId];
            $processList            = Process::getList($where)->toArray();
            foreach($processTypeList as $key=>$val)
            {

                $tempList           = [];
                foreach($processList as $k=>$v)
                {
                    if($v['type']==$val['id'])
                    {
                        $tempList[] = $v;
                    }
                }
                $valTitle           = $val['title'];
                if($val['id']==0)
                {
                    $valTitle       = '未知分类';
                }
                if(empty($tempList)){
                    $valTitle       .= '(暂无工序)';
                }
                $processTypeList[$key]['title'] = $valTitle;
                $processTypeList[$key]['data']  = $tempList;
            }

            return $this->view('process-add', compact('orderTypeId', 'processTypeList'));
        }
    }

    public function editOrderTypeProcess(){
        $input = $this->requestJson();
        $updateData = [
            'step_number'=>$input['step_number'],
            'is_over'=>$input['is_over'],
            'meanwhile_next_step'=>$input['meanwhile_next_step'],
        ];
        $processOrdertypeModel = new ProcessOrdertype();
        $where = ['id'=>$input['id']];
        $result = $processOrdertypeModel->updateOneData($where, $updateData);
        if($result){
            return $this->ajaxSuccess('编辑成功！');
        }else{
            return $this->ajaxFail('编辑失败，请重试！');
        }
    }

    public function setOrderTypeProcessAction(){
        if (request()->isMethod('post')) {
            $id = request('id');
            $actions = request('actions',[]);
            $actionsStr = implode(',',$actions);
            $processOrdertypeModel = new ProcessOrdertype();
            $updateData = ['actions'=>$actionsStr];
            $where = ['id'=>$id];
            $result = $processOrdertypeModel->updateOneData($where, $updateData);
            if($result){
                return $this->ajaxSuccess();
            }else{
                return $this->ajaxFail();
            }
        }
        $id = request('id');

        $where = ['id'=>$id];
        $processOrdertypeModel = new ProcessOrdertype();
        $info = $processOrdertypeModel->getOneData($where);

        $actions = explode(',',$info['actions']);

        $allActions = collect(Permission::getTypeActionList( 1 ));

        $allActions->transform(function ($item, $key) use($actions) {
            $item['isCheck'] = in_array($item['id'],$actions) ? 1 : 0;
            return $item;
        });

        return $this->view('set-process-action', compact('allActions','id'));
    }



/*
    public function setOrderTypeProcess(){
        if (request()->isMethod('post')) {
            dd(request()->all());
            $orderTypeId = request('ordertype_id');
            $steps = request('step');
            $processIds = request('process_id');
            $stepNumbers = array_combine($processIds,$steps);

            $cdata = [];
            $delData = [];
            foreach ($stepNumbers as $key => $val){
                if($val){
                    $cdata[] = ['ordertype_id'=>$orderTypeId,'process_id'=>$key,'step_number'=>$val];
                }else{
                    $delData[] = ['ordertype_id'=>$orderTypeId,'process_id'=>$key];
                }
            }
            $processOrdertypeModel = new ProcessOrdertype();

            //删除没有设置步骤的工序
            foreach ($delData as $v){
                $delResult = $processOrdertypeModel->del($v);
            }


            if($processOrdertypeModel->addProcessOrderType($cdata)){
                return $this->jsonReturn('ok');
            }

        }else{
            $orderTypeId = request('orderTypeId');
            $ProcessModel = new Process();
            $list = $ProcessModel->getProcessListWithStep($orderTypeId);
//            dd($list->toArray());
            return $this->view('set-process', compact('list','orderTypeId'));
        }

    }*/
    public function addOrderType()
    {
        if (request()->isMethod('post')) {
            $createData = request()->only('title','img_id','category_id');
            $adminUser          = request()->user('admin')->toArray();
            $company_id         = $adminUser['company_id'];
            $createData['company_id'] = $company_id;

            $orderTypeModel = new orderType();
            if($result = $orderTypeModel->insertData($createData)){
                return $this->ajaxSuccess('添加成功');
            }else{
                return $this->ajaxFail('添加失败');
            }
        }

        $adminUser          = request()->user('admin')->toArray();
        $company_id         = $adminUser['company_id'];

        $orderTypeCategoryModel = new OrdertypeCategory();
        $categoryList = $orderTypeCategoryModel->getData(['company_id'=>$company_id],'id,cat_name')->toArray();

        return $this->view('add', compact('categoryList'));
    }

    public function editOrderType()
    {
        if (request()->isMethod('post')) {
            $createData = request()->only('title','img_id','category_id');
            $where = ['id'=>request('id')];
            $orderTypeModel = new orderType();
            if($result = $orderTypeModel->updateOneData($where, $createData)){
                return $this->ajaxSuccess('保存成功');
            }else{
                return $this->ajaxFail('保存失败');
            }
        }

        if($id = request('orderTypeId')){

            $orderTypeModel = new orderType();
            $where = ['id'=>$id];
            $info = $orderTypeModel->getOneData($where);
            $info->img_url = Func::getImgUrlById($info->img_id);

            $adminUser          = request()->user('admin')->toArray();
            $company_id         = $adminUser['company_id'];

            $orderTypeCategoryModel = new OrdertypeCategory();
            $categoryList = $orderTypeCategoryModel->getData(['company_id'=>$company_id],'id,cat_name')->toArray();


            return $this->view('edit', compact('info','categoryList'));
        }else{
            return 'ok';
        }
    }

    public function deleteOrderType(){
        $id = request('id');
        $where = ['id'=>$id];
        $orderTypeModel = new orderType();
        if($orderTypeModel->del($where)){
            return $this->ajaxSuccess('删除成功');
        }else{
            return $this->ajaxFail('删除失败');
        }
    }

    //工序废品设置
    public function setOrderTypeProcessWaste(){
        $ordertypeProcessId = request('id');
        $orderTypeId = request('orderTypeId');


        return $this->view('set-process-waste', compact('ordertypeProcessId'));

    }

    //工序废品设置-数据
    public function processWasteList(){
        $ordertypeProcessId = request('ordertypeProcessId');

        //获取对应的废品信息
        $ordertypeProcessWasteList = \App\Eloquent\Ygt\OrdertypeProcessWaste::where(['ordertype_process_id'=>$ordertypeProcessId])->get();
        $ordertypeProcessWasteList->transform(function ($item, $key){
            //增加操作时间
            $itemArr = $item->toArray();
            $operateTime = date('Ymd H:i:s',$itemArr['updated_at']);
            $item['operate_time'] = $operateTime;

            return $item;
        });

        return $ordertypeProcessWasteList;


    }

    //工序废品设置-编辑
    public function processWasteEdit(){
        $ordertypeProcessId = request('ordertypeProcessId');
        //获取对应的工序ID
        $processId = \App\Eloquent\Ygt\ProcessOrdertype::where(['id'=>$ordertypeProcessId])->first()->process_id;

        $params             = $this->requestJson();
        $id = $params['id'];
        $title = $params['title'];
        if(!$title){
            return $this->ajaxFail( '请填写内容' );
        }

        $ordertypeProcessWasteObj = \App\Eloquent\Ygt\OrdertypeProcessWaste::firstOrNew(['id'=>$id]);
        $editRow = [
            'ordertype_process_id' => $ordertypeProcessId,
            'process_id' => $processId,
            'title' => $title,
        ];
        $ordertypeProcessWasteObj->fill($editRow);
        $ordertypeProcessWasteObj->save();

        //修改对应废品库存的信息（如存在）
        $wasteObj = \App\Eloquent\Ygt\Waste::where(['relate_type'=>2,'relate_id'=>$ordertypeProcessWasteObj->id])->first();
        if($wasteObj){
            $wasteObj->waste_name = $title;
            $wasteObj->save();
        }


        return $this->ajaxSuccess('操作成功');
    }

    //工序废品设置-编辑
    public function processWasteDelete(){
        $id = request('id');
        $ordertypeProcessWasteObj = \App\Eloquent\Ygt\OrdertypeProcessWaste::where(['id'=>$id])->delete();

        //修改对应废品库存的信息（如存在）
        $wasteObj = \App\Eloquent\Ygt\Waste::where(['relate_type'=>2,'relate_id'=>$id])->first();
        if($wasteObj){
            $wasteObj->waste_name = $wasteObj->waste_name."【已删除】";
            $wasteObj->save();
        }

        return $this->ajaxSuccess('操作成功');
    }


    //工序半成品设置
    public function setOrderTypeProcessProduct(){
        $ordertypeProcessId = request('id');
        $orderTypeId = request('orderTypeId');

        return $this->view('set-process-product', compact('ordertypeProcessId'));
    }

    //工序半成品列表
    public function processProductList(){
        $ordertypeProcessId = request('ordertypeProcessId');

        //获取对应的废品信息
        $ordertypeProcessWasteList = \App\Eloquent\Ygt\ProcessProduct::where(['ordertype_process_id'=>$ordertypeProcessId])->get();
        $ordertypeProcessWasteList->transform(function ($item, $key){
            //增加操作时间
            $itemArr = $item->toArray();
            $operateTime = date('Ymd H:i:s',$itemArr['updated_at']);
            $item['operate_time'] = $operateTime;

            return $item;
        });

        return $ordertypeProcessWasteList;
    }

    //工序废品设置-编辑
    public function processProductEdit(){
        $ordertypeProcessId = request('ordertypeProcessId');
        //获取对应的工序ID
        $processId = \App\Eloquent\Ygt\ProcessOrdertype::where(['id'=>$ordertypeProcessId])->first()->process_id;

        $params             = $this->requestJson();
        $id = $params['id'];
        $title = $params['title'];
        if(!$title){
            return $this->ajaxFail( '请填写内容' );
        }

        $tmpProcessProductObj = \App\Eloquent\Ygt\ProcessProduct::firstOrNew(['id'=>$id]);
        $editRow = [
            'ordertype_process_id' => $ordertypeProcessId,
            'process_id' => $processId,
            'title' => $title,
        ];
        $tmpProcessProductObj->fill($editRow);
        $tmpProcessProductObj->save();


        return $this->ajaxSuccess('操作成功');
    }





}